# -*- coding:utf-8 -*-
from database.db_business import DbBusiness
from common.my_time import MyTime
from common.my_baidu import MyBaidu
from common.attr_v3 import AttrV3
from common.my_file import MyFile
from bs4 import BeautifulSoup
import glob
import jieba
import re
import threading
import hashlib
import urllib.parse
import time
import os

'''
网络数据
'''

class BaiduStockPingji:
    def __init__(self):
        self.attr_v3 = AttrV3()
        self.business = DbBusiness()
        self.log_file = open('./out/' + os.path.split(__file__)[-1].split(".")[0] + ".log", 'a', encoding = 'utf-8')
        MyFile.wrtie_log(self.log_file, "开始")
        #self.market = MarketData()

    def __del__(self):
        MyFile.wrtie_log(self.log_file, "结束")
        self.log_file.close()

    def check_site(self, site_name):
        site_lists = ["新浪","东方财富网","同花顺","每日经济新闻","和讯","第一财经","证券时报","经济观察报","中国财经信息网"]
        for d in site_lists:
            if re.search(d, site_name):
                return True
        print(site_name)
        return False
    
    def get_data(self):
        datas = self.business.query_stock_code_name()
        end_date = MyTime.forward_relative_date(5)
        check_title1 = ["评级"]
        check_title2 = ["目标价"]
        for k,v in datas.items():
            next_page = True
            words = ["\"" + v + "\"", "机构评级"]
            for i in range(1,2):
                #time.sleep(1)
                if next_page == False:
                    break
                url = MyBaidu.get_url_order_by_time(words, i)
                try:
                    proxy = self.business.query_proxy()
                    res = MyBaidu.get_baidu_data_by_proxy(url, proxy)
                    for r in res:
                        data_date = MyBaidu.calc_date(r["date"])
                        if data_date < end_date:
                            next_page = False
                            break
                        if self.check_site(r["site"]) == False:
                            continue
                        if MyBaidu.check_title(r["title"], [[v], check_title1, check_title2]) == False:
                            continue
                        data_title = r["title"]
                        data_site = r["site"]
                        data_url = r["url"]
                        print(r["date"] + data_date)
                        table_name = self.attr_v3.get_table_name(3004)
                        self.attr_v3.add_attr_data(table_name, k, data_title, data_date, data_url, data_site)
                except Exception as e:
                    #i = i - 1
                    pass

if __name__ == '__main__':
    lock_file = open('./out/' + os.path.split(__file__)[-1].split(".")[0] + ".lock", 'a', encoding = 'utf-8')
    if False == MyFile.lock_file(lock_file):
        quit()
    d = BaiduStockPingji()
    d.get_data()
